project(
    'extension_cpp',
    'cpp',
    'cuda',
    version: '0.0.1',
    default_options: [
        'cpp_std=c++17',
        'warning_level=2',
        'buildtype=release', # 默认 Release
    ],
)

# ---------- 选项 ----------
# 1. debug 开关
debug_opt = get_option('buildtype') == 'debug'
# 2. 是否启用 CUDA
use_cuda = get_option('use_cuda') # 默认自动检测

# ---------- Python ----------
py_mod = import('python')
py = py_mod.find_installation(pure: false, required: true)

# 手动指定链接库，避免使用 embed: true
if true
    py_dir_libs = py.get_variable('BINDIR') / 'libs' #  Python/Python312/libs 目录
    py_lib_name = 'python' + py.get_variable('py_version_nodot') # .lib 导出库名称, 例如 'python312'
    py_dep = declare_dependency(
        include_directories: include_directories(py.get_variable('INCLUDEPY')),
        link_args: ['-L' + py_dir_libs, '-l' + py_lib_name],
    )
else
    py_dep = py.dependency()
endif

# ---------- 手工找 Torch ----------
# 1. 先试试 pkg-config（官方 wheel 没有，基本会失败）
torch_dep = dependency('torch', required: false)

# 2. pkg-config 找不到就走 fallback
if not torch_dep.found()
    ##----- 直接添加
    torch_base = 'C:/cppLibs/libtorch'
    torch_inc = include_directories(
        torch_base / 'include',
        torch_base / 'include/torch/csrc/api/include',
    )
    torch_lib = torch_base / 'lib'
    # message(torch_inc)
    message(torch_lib)

    # 2-3 自己 declare 一个 dependency
    torch_dep = declare_dependency(
        include_directories: torch_inc,
        link_args: [
            '-L' + torch_lib,
            '-ltorch',
            '-ltorch_cpu',
            '-ltorch_cuda',
            '-lc10',
            '-lc10_cuda',
        ],
        # 如果开了 CUDA 再加 -ltorch_cuda
        dependencies: py_dep, # 别忘了 Python 本身
    )
endif

# ---------- 源文件 ----------
cpp_src = files('extension_cpp/csrc/muladd.cpp')
if use_cuda
    cuda_src = files('extension_cpp/csrc/cuda/muladd.cu')
else
    cuda_src = []
endif

# ---------- 编译参数 ----------
cpp_args = ['-DPy_LIMITED_API=0x03090000'] # cp39 limited api
if debug_opt
    cpp_args += ['-O0', '-g']
else
    cpp_args += ['-O3']
endif

cuda_args = []
if cuda_src.length() > 0
    cuda_args += ['-O3'] # nvcc 默认 Release 已经带 -O3，这里显式写
    if debug_opt
        cuda_args += ['-g', '-G']
    endif
endif

# ---------- 生成扩展模块 ----------
py.extension_module(
    '_C',
    cpp_src + cuda_src,
    cpp_args: cpp_args,
    cuda_args: cuda_args,
    dependencies: [py_dep, torch_dep],
    install: true,
    subdir: 'extension_cpp', # 安装到 site-packages/extension_cpp/
    limited_api: '3.9',
)